<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>简易聊天室</title>
	<style type="text/css">
		div{
			width: 600px;
			height: 600px;
			border: 1px solid red;
		}
		textarea{
			width: 200px;
			height: 200px;
		}
	</style>
</head>
<body>
	<div></div>
	<textarea>123</textarea>
	<button onclick="send_text()">发送</button>
	<input type="hidden" id="uid" value="{$uid}">
	<br>
	可聊天用户:
	<br>
	{foreach $data as $key=>$vo } 
		{$vo.username}<input type="radio" value="{$vo.id}" id="user_id" name="name1">
	{/foreach}
</body>
</html>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
	var text = $('textarea').val();
	var ws = new WebSocket("ws://192.168.1.131:8081");
	// console.log(ws);
	//连接
	ws.onopen = function()
	{
		var uid = $('#uid').val();
		// console.log('{"text":'+text+',"uid":"1"}');return;
		ws.send('{"text":'+text+',"uid":'+uid+', "action":"login"}');
		alert("登录中...");
	};
	
	//接收
	ws.onmessage = function (evt) 
	{
		// console.log(JSON.parse( evt.data ));
		var data = JSON.parse( evt.data );
		console.log(data);
		if(data.action == 'connect') {
			alert(data.text);
		}
		if(data.action == 'message') {
			$('div').append('<span>'+data.text+'</span><br/>');
		}
		if(data.action == 'error') {
			alert(data.text);
		}
		if(data.action == 'login_out') {
			alert(data.text);
		}
		
	};
	//发送
	function send_text() {
		var text = $('textarea').val();
		// var user_id = $('#user_id').val();
		var user_id = $("input[type=radio]:checked").val()
		console.log(text);
		ws.send('{"text":"'+text+'", "action":"message", "user_id":'+user_id+'}');
		// console.log(text);
	}


			

</script>